package com.house.keep.controller;


import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;


/**
 * @author lkz
 * @className DemoController
 * @description
 * @date 2024/7/9 11:20
 **/
@RestController
@RequestMapping("/demo")
public class DemoController {

    @Resource
    private DataSource dataSource;


    @GetMapping("/test")
    public void executeSqlScript() throws IOException {
        ClassPathResource resource = new ClassPathResource("init.sql");
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

        List<String> sqlStatements = readSqlFile(resource);
        for (String sql : sqlStatements) {
            sql = sql.replace("dict_id = '@dict_id'", "dict_id = '" + 9 + "'");
            jdbcTemplate.execute(sql);
        }


    }


    private List<String> readSqlFile(ClassPathResource resource) throws IOException {
        List<String> sqlStatements = new ArrayList<>();
        StringBuilder sqlBuilder = new StringBuilder();

        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))) {

            String line;
            while ((line = reader.readLine()) != null) {
                // 去除行尾的空格和可能的分号
                line = line.trim();

                // 检查是否以分号结尾，并且不是空行
                if (!line.isEmpty() && line.endsWith(";")) {
                    // 移除行尾的分号
                    line = line.substring(0, line.length() - 1);
                    // 将当前行添加到之前累积的SQL语句中，并作为一个完整的语句添加到列表中
                    sqlBuilder.append(line).append(" ");
                    sqlStatements.add(sqlBuilder.toString().trim());
                    // 重置StringBuilder以准备下一个SQL语句
                    sqlBuilder.setLength(0);
                } else {
                    // 如果不是以分号结尾，则继续累积到StringBuilder中
                    sqlBuilder.append(line).append(" ");
                }
            }

            // 处理文件中最后一个SQL语句不以分号结尾的情况
            if (sqlBuilder.length() > 0) {
                sqlStatements.add(sqlBuilder.toString().trim());
            }

        }

        return sqlStatements;
    }

}
